package com.yanqu.road.server.manger.location;

import com.github.houbb.opencc4j.util.ZhConverterUtil;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.language.LanguageType;
import com.yanqu.road.entity.location.LocationExtend;
import com.yanqu.road.entity.location.LocationInfo;
import com.yanqu.road.entity.servercenter.IpInfo;
import com.yanqu.road.logic.bussiness.config.LocationInfoBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.Objects;

public class LocationMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(LocationMgr.class.getName());

//    // 根据id 查找地理位置信息
//    private static Map<Integer, LocationInfo> locationIdMap;
//
//    // 根据国家编码查找地理位置信息
//    private static Map<String, List<LocationInfo>> countryLocationMap;

    // 用来修改地理位置的配置信息
    private static Map<Integer, LocationExtend> locationExtendMap;

    // This creates the DatabaseReader object. To improve performance, reuse
    // the object across lookups. The object is thread-safe.
//    private static DatabaseReader reader;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean reloadConfig() {
//        locationIdMap = LocationInfoBussiness.getLocationInfoIdMap();
//        if (locationIdMap == null) {
//            return false;
//        }
        locationExtendMap = LocationInfoBussiness.getLocationExtendMap();
        if (locationExtendMap == null || locationExtendMap.size() <= 0) {
            return false;
        }

//        Map<String, List<LocationInfo>> tempMap = new ConcurrentHashMap<>();
//        for (LocationInfo locationInfo : locationIdMap.values()) {
//            if (!tempMap.containsKey(locationInfo.getCountryCode())) {
//                tempMap.put(locationInfo.getCountryCode(), new ArrayList<>());
//            }
//            List<LocationInfo> locationInfos = tempMap.get(locationInfo.getCountryCode());
//            locationInfos.add(locationInfo);
//        }
//        countryLocationMap = tempMap;

//        String filePath = ConfigHelper.getValue("geoLitePath");
//        if (filePath == null) {
//            logger.error("加载 GeoLite2 失败， 文件路径为null");
//            return false;
//        }
//        File database = new File(filePath);
//        try {
//            reader = new DatabaseReader.Builder(database).build();
//        } catch (IOException e) {
//            logger.error("加载 GeoLite2 失败， 文件路径: {}", filePath, e);
//        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

//    public static LocationInfo getLocationInfoByCityId(int cityId) {
//        return locationIdMap.get(cityId);
//    }

    /**
     * 港澳台、韩国、日本渠道不用ip定位地理信息，直接使用默认地理信息
     * @param channelId
     * @return
     */
    public static boolean isUseDefaultLocation(int channelId){
        eChannelType eChannelType = com.yanqu.road.entity.enums.eChannelType.forValue(channelId);
        if (eChannelType == null) {
            return true;
        }
        return !eChannelType.isUseIpLocation();
    }

    /**
     * 根据地理位置id和城市名称确定地理位置信息
     */
    public static LocationExtend findLocationExtend(int id, String city) {
        LocationExtend location = locationExtendMap.get(id);
        if (location == null || !location.getCitys().contains(city)) {
            return null;
        }
        return location;
    }

    /**
     * 获取默认地理位置
     * @param type  0:世界，1:洲,2:国家,3:省,4:城市
     */
    private static String getDefaultLocation(int type, String language) {
        if (type < 0 || type > 4) {
            return "";
        }
        String location = MultipleLanguageMgr.getContent(GameConfig.DEFAULT_LOCATION, language);
        String[] locationArr = location.split(";");
        if(type >= locationArr.length){
            return "";
        }
        return locationArr[type];
    }

    /**
     * 获取默认地理位置
     */
    public static LocationInfo getDefaultLocation(String language) {
        LocationInfo locationInfo = new LocationInfo();
        locationInfo.setId(0);
        locationInfo.setWorld(getDefaultLocation(0, language));
        locationInfo.setContinent(getDefaultLocation(1, language));
        locationInfo.setCountry(getDefaultLocation(2, language));
        locationInfo.setProvince(getDefaultLocation(3, language));
        locationInfo.setCity(getDefaultLocation(4, language));
        return locationInfo;
    }

    public static LocationInfo getLocationInfoByIp(String ip, String language) {
        LocationInfo locationInfo = null;
        try {
            IpInfo ipInfo = IpMgr.getIpInfo(ip);
            if(null != ipInfo && !StringUtils.isNullOrEmpty(ipInfo.getCountry()) && !StringUtils.isNullOrEmpty(ipInfo.getProvince())
                    && !StringUtils.isNullOrEmpty(ipInfo.getCity())){
                locationInfo = new LocationInfo();
                locationInfo.setId(0);
                locationInfo.setWorld(getDefaultLocation(0, language));
                locationInfo.setContinent(getDefaultLocation(1, language));
                locationInfo.setCountry(ipInfo.getCountry());
                locationInfo.setProvince(ipInfo.getProvince());
                locationInfo.setCity(ipInfo.getCity());
                if(Objects.equals(language, LanguageType.LANGUAGE_TW)) {
                    if(ConfigMgr.isNeedTranslateLocationCity(locationInfo.getCity())){//如果是一些需要转成台湾城市的地方，先转
                        locationInfo.setCountry(getDefaultLocation(2, language));
                        locationInfo.setProvince(getDefaultLocation(3, language));
                        locationInfo.setCity(ConfigMgr.getLocationCity(locationInfo.getCity()));
                    }
                    if(Objects.equals("台湾", locationInfo.getProvince())){
                        locationInfo.setCountry(getDefaultLocation(2, language));
                        locationInfo.setProvince(getDefaultLocation(3, language));
                    }else {
                        locationInfo.setCountry(ZhConverterUtil.toTraditional(locationInfo.getCountry()));
                        locationInfo.setProvince(ZhConverterUtil.toTraditional(locationInfo.getProvince()));
                    }
                    if(!ConfigMgr.isNoTranslateCity(locationInfo.getCity())) {
                        locationInfo.setCity(ZhConverterUtil.toTraditional(locationInfo.getCity()));
                    }
                }
            }
        }catch (Exception e) {
            logger.warn(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
            logger.warn("找不到ip信息， ip: {}", ip);
        }
        if(null == locationInfo){
            locationInfo = getDefaultLocation(language);
        }
        return locationInfo;
    }

//    public static LocationInfo getLocationInfoByIp(String ip) {
//        try {
//            InetAddress ipAddress = InetAddress.getByName(ip);
//            CityResponse resp = reader.city(ipAddress);
//            if (resp != null) {
//                Country country = resp.getCountry();
//                Integer geoNameId = country.getGeoNameId();
//                if (geoNameId == eCountryType.CHN.getGeoId()) {
//                    // 大陆 还是优先使用淘宝ip库吧
//                    IpInfo ipInfo = IpMgr.getIpInfo(ip);
//                    if (ipInfo != null) {
//                        LocationInfo locationInfo = getLocationInfoByCityId(ipInfo.getCityId());
//                        if (locationInfo == null) {
//                            locationInfo = new LocationInfo();
//                            locationInfo.setId(0);
//                            locationInfo.setWorld(getDefaultLocation(0, LanguageType.LANGUAGE_DEFAULT));
//                            locationInfo.setContinent(getDefaultLocation(1, LanguageType.LANGUAGE_DEFAULT));
//                            locationInfo.setCountry(ipInfo.getCountry());
//                            locationInfo.setProvince(ipInfo.getProvince());
//                            locationInfo.setCity(ipInfo.getCity());
//                        }
//                        return locationInfo;
//                    }
//                    City city = resp.getCity();
//                    return getLocationInfo(resp, city.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//
//                } else if (geoNameId == eCountryType.TW.getGeoId()) {
//                    // 台湾 使用城市
//                    IpInfo ipInfo = IpMgr.getIpInfo(ip);
//                    if (ipInfo != null) {
//                        LocationInfo locationInfo = getLocationInfoByCityId(ipInfo.getCityId());
//                        if (locationInfo == null) {
//                            locationInfo = new LocationInfo();
//                            locationInfo.setId(0);
//                            locationInfo.setWorld(getDefaultLocation(0, LanguageType.LANGUAGE_TW));
//                            locationInfo.setContinent(getDefaultLocation(1, LanguageType.LANGUAGE_TW));
//                            locationInfo.setCountry(ipInfo.getCountry());
//                            locationInfo.setProvince(ipInfo.getProvince());
//                            locationInfo.setCity(ipInfo.getCity());
//                        }
//                        return locationInfo;
//                    }
//                    City city = resp.getCity();
//                    return getLocationInfo(resp, city.getGeoNameId(), LanguageType.LANGUAGE_TW);
//                } else if (geoNameId == eCountryType.HK.getGeoId()) {
//                    // 香港使用 subdivision
//                    Subdivision subdivision = resp.getMostSpecificSubdivision();
//                    return getLocationInfo(resp, subdivision.getGeoNameId(), LanguageType.LANGUAGE_TW);
//                } else if (geoNameId == eCountryType.MYS.getGeoId()) {
//                    // 马来西亚
//                    Subdivision subdivision = resp.getMostSpecificSubdivision();
//                    return getLocationInfo(resp, subdivision.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//                } else if (geoNameId == eCountryType.SGP.getGeoId()) {
//                    // 新加坡
//                    City city = resp.getCity();
//                    return getLocationInfo(resp, city.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//                } else if (geoNameId == eCountryType.THA.getGeoId()) {
//                    // 泰国
//                    Subdivision subdivision = resp.getMostSpecificSubdivision();
//                    return getLocationInfo(resp, subdivision.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//                } else if (geoNameId == eCountryType.PHL.getGeoId()) {
//                    //菲律宾
//                    Subdivision subdivision = resp.getMostSpecificSubdivision();
//                    return getLocationInfo(resp, subdivision.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//                }else if (geoNameId == eCountryType.IDN.getGeoId()){
//                    // 印尼
//                    Subdivision subdivision = resp.getMostSpecificSubdivision();
//                    return getLocationInfo(resp, subdivision.getGeoNameId(), LanguageType.LANGUAGE_DEFAULT);
//                }else {
//                    return getLocationInfoWhenCityIsNull(resp);
//                }
//            }
//        } catch (Exception e) {
//            logger.warn(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
//            logger.error("找不到ip信息， ip: {}", ip);
//        }
//        return null;
//    }
//
//    private static LocationInfo getLocationInfo(CityResponse resp, Integer geoNameId, String language) {
//        if (geoNameId != null) {
//            LocationInfo locationInfo = getLocationInfoByCityId(geoNameId);
//            if (locationInfo != null) {
//                locationInfo.setWorld(getDefaultLocation(0, language));
//                locationInfo.setContinent(getDefaultLocation(1, language));
//                return locationInfo;
//            }
//        }
//        return getLocationInfoWhenCityIsNull(resp);
//    }
//
//    /**
//     * 当ip拿不到时，会有经纬度信息，再次获取定位信息
//     */
//    private static LocationInfo getLocationInfoWhenCityIsNull(CityResponse resp) {
//        Location location = resp.getLocation();
//        if (location != null) {
//            Double lat = location.getLatitude();
//            Double longitude = location.getLongitude();
//            return getLocationInfoByCoordinate(String.valueOf(lat), String.valueOf(longitude));
//        }
//        return null;
//    }
//
//    /**
//     * 根据经纬度获取地理信息
//     */
//    public static LocationInfo getLocationInfoByCoordinate(String lat, String lng) {
//        try {
//            JSONObject location = LocationHelper.getLocation(lat + "," + lng);
//            if (location != null) {
//                BaiduLocation baiduLocation = JSONObject.parseObject(location.toJSONString(), BaiduLocation.class);
//                switch (baiduLocation.getCountry_code_iso()) {
//                    case "MYS":
//                        //马来西亚
//                        return getMYSLocationInfo(baiduLocation);
//                    case "SGP":
//                        // 新加坡
//                        return getSGPLocationInfo(baiduLocation);
//                    case "THA":
//                        return getTHALocationInfo(baiduLocation);
//                    case "PHL":
//                        return getPHLLocationInfo(baiduLocation);
//                    case "IDN":
//                        return getIDNLocation(baiduLocation);
//                    case "CHN":
//                        // 中国
//                        String province = baiduLocation.getProvince();
//                        if (province.contains("香港")) {
//                            return getHKLocationInfo(baiduLocation);
//                        } else if (province.contains("台湾")) {
//                            return getTWLocationInfo(baiduLocation);
//                        } else {
//                            // 大陆地区
//                            return getChineseMainLandLocationInfo(baiduLocation);
//                        }
//                    default:
//                        LocationInfo locationInfo = new LocationInfo();
//                        locationInfo.setId(0);
//                        locationInfo.setWorld("世界");
//                        locationInfo.setContinent("亚洲");
//                        locationInfo.setCountry(baiduLocation.getCountry());
//                        locationInfo.setProvince(baiduLocation.getProvince());
//                        locationInfo.setCity(baiduLocation.getCity());
//                        return locationInfo;
//
//                }
//            }
//        } catch (Exception ex) {
//            logger.warn(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", ex);
//        }
//        return null;
//    }
//
//    private static LocationInfo getIDNLocation(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.IDN.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getProvince())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }
//
//    private static LocationInfo getPHLLocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.PHL.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getCity())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }
//
//    private static LocationInfo getTHALocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.THA.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getProvince())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }
//
//    private static LocationInfo getChineseMainLandLocationInfo(BaiduLocation baiduLocation) {
//        LocationInfo locationInfo = new LocationInfo();
//        locationInfo.setId(0);
//        locationInfo.setWorld("世界");
//        locationInfo.setContinent("亚洲");
//        locationInfo.setCountry(baiduLocation.getCountry());
//        locationInfo.setProvince(baiduLocation.getProvince());
//        locationInfo.setCity(baiduLocation.getCity());
//        return locationInfo;
//    }
//
//    private static LocationInfo getTWLocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.TW.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getCity())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }
//
//    private static LocationInfo getHKLocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.HK.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getDistrict())) {
//                return locationInfo;
//            }
//        }
//
//        return null;
//    }
//
//    private static LocationInfo getSGPLocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.SGP.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getProvince())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }
//
//    private static LocationInfo getMYSLocationInfo(BaiduLocation baiduLocation) {
//        List<LocationInfo> locationInfos = countryLocationMap.get(eCountryType.MYS.getCode());
//        for (LocationInfo locationInfo : locationInfos) {
//            if (locationInfo.getCity().equals(baiduLocation.getProvince())) {
//                return locationInfo;
//            }
//        }
//        return null;
//    }


}
